package com.example.smartplay.controller;


import com.example.smartplay.entity.Result;
import com.example.smartplay.entity.Student;
import com.example.smartplay.entity.User;
import com.example.smartplay.mapper.StudentMapper;
import com.example.smartplay.mapper.UserMapper;
import com.example.smartplay.service.StudentService;
import com.example.smartplay.service.UserService;
import com.example.smartplay.utils.EmailUtil;
import com.example.smartplay.utils.JwtUtil;
import com.example.smartplay.utils.Md5Util;
import com.example.smartplay.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpSession;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author
 * @since 2024-07-11
 */
@RestController
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;
    @Autowired
    EmailUtil emailUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private StudentMapper studentMapper;

    //注册
    @PostMapping("/register")
    public Result register(String username, String password, String password2, String email, String code1, HttpSession session) {
        // 判断两次输入的密码是否一致
        if (!password.equals(password2)) {
            return Result.error("两次输入的密码不一致");
        }

        // 查询用户是否存在
        Student student = studentService.findByUsername(username);
        if (student != null) {
            return Result.error("用户已存在");
        }
        //查询邮箱是否存在
        Student existingStudent = userMapper.findByEmail(email);
        if (existingStudent != null) {
            return Result.error("邮箱已存在");
        }
        // 判断邮箱和验证码是否匹配
        String sessionEmail = (String) session.getAttribute("register_email");
        String sessionCode = (String) session.getAttribute("register_code");

        if (!email.equals(sessionEmail)) {
            return Result.error("邮箱与验证码不匹配");
        }
        if (!code1.equals(sessionCode)) {
            return Result.error("验证码错误");
        }

        // 清除 session 中的验证码和邮箱信息，防止重复使用
        session.removeAttribute("register_email");
        session.removeAttribute("register_code");
        // 注册用户
        studentService.register(username, password);
        // 获取注册成功的学生信息
        Student registeredStudent = studentService.findByUsername(username);
        // 将邮箱信息存入 user 表中
        User user = new User();
        user.setStudentId(registeredStudent.getId());
        user.setEmail(email);
        user.setRole("USER");

        userMapper.insert(user);
        return Result.success();

    }

    //登录
    @PostMapping("/login")
    public Result login(String username, String password) {
        //查询用户是否存在
        Student student = studentService.findByUsername(username);
        if (student == null) {
            return Result.error("用户名或密码错误");
        } else {
            if (Md5Util.getMD5String(password).equals(student.getPassword())) {
                //登录成功
                //通过学生studentid查询对应user表
                User user = userMapper.selectByStudentId(student.getId());
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", student.getId());
                claims.put("username", student.getUsername());
                claims.put("level", user.getLevel());
                claims.put("club_id",user.getClubId());
                claims.put("role", user.getRole());


                String token = JwtUtil.genToken(claims);
                return Result.success(token);

            } else {
                return Result.error("用户名或密码错误");
            }
        }
    }

    //分页查询学生
    @RequestMapping("/getstudent/{pageNum}/{pageSize}")
    public Result getstudent(
            @PathVariable("pageNum") Integer pageNum,
            @PathVariable("pageSize") Integer pageSize
    ) {
        return studentService.getstudent(pageNum, pageSize);
    }

    //修改或者更新学生
    @PostMapping("/saveOrUpdate")
    public Result saveOrUpdate(@RequestBody Student student) {
        studentService.saveOrUpdate(student);
        return Result.success();
    }

    //删除学生
    @DeleteMapping("{ids}")
    public Result delete(@PathVariable List<Integer> ids) {
        studentService.removeByIds(ids);
        return Result.success();
    }
    //发送邮件

    @GetMapping("/sendEmail")
    public String sendEmail(String email, HttpSession session) {
        String code = RandomStringUtils.randomNumeric(4);
        session.setAttribute("register_email", email); // 注册时使用的邮箱
        session.setAttribute("register_code", code);  // 注册时使用的验证码
        emailUtil.sendSimpleMessage(email, "欢迎注册", "您的验证码为" + code);
        return code;
    }

    //查询所有身份为1的学生
    @GetMapping("/getlevel")
    public Result getAllHeaders(Student student) {
        List<Student> AllHeaders = studentService.selectAllHeaders(student);
        return Result.success(AllHeaders);
    }

    //修改密码
    @PostMapping("/updatePassword")
    public Result updatePassword(//@RequestHeader("Authorization") String tokenHeader,
                                 @RequestParam("oldPassword") String oldPassword,
                                 @RequestParam("newPassword") String newPassword,
                                 @RequestParam("newPassword2") String newPassword2) {


        if (newPassword == null || newPassword2 == null || !newPassword.equals(newPassword2)) {
            return Result.error("两次输入的密码不一致或密码为空");
        }
        //如果旧密码和新密码相同
        if (oldPassword.equals(newPassword)) {
            return Result.error("新密码不能与旧密码相同");
        }
        //解析token 并获取到studnetid
       /*  Map<String, Object> claims = JwtUtil.parseToken(tokenHeader);
        Integer studentId = (Integer) claims.get("id");*/


        Map<String, Object> map = ThreadLocalUtil.get();
        Integer studentId = (Integer) map.get("id");


        Student student = studentMapper.selectById(studentId);
        if (student == null) {
            return Result.error("找不到对应的学生信息");
        }

        // 验证旧密码
        if (Md5Util.getMD5String(oldPassword).equals(student.getPassword())) {
            // 更新密码
            student.setPassword(Md5Util.getMD5String(newPassword));
            studentService.updateById(student);
            return Result.success();
        } else {
            return Result.error("旧密码错误");
        }
    }

}
